package http

import (
	"net/http"
	"strconv"

	"gitee.com/ldysdy999/hostdemon/app/host"
	"github.com/infraboard/mcube/http/request"
	"github.com/infraboard/mcube/http/response"
	"github.com/julienschmidt/httprouter"
)

//创建host
func (h *handler) CreateHost(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
	// body, err := request.ReadBody(r)
	// if err != nil {
	// 	response.Failed(w, err)
	// 	return
	// }
	// h.log.Debugf("body is %s", body)
	req := host.NewDefaultHost()
	//解析HTTP协议，通过json反序列化，JSON --> Request
	if err := request.GetDataFromRequest(r, req); err != nil {
		response.Failed(w, err)
		h.log.Debugf("cuowu")
		return
	}

	ins, err := h.host.CreateHost(r.Context(), req)
	if err != nil {
		response.Failed(w, err)
		return
	}
	response.Success(w, ins)
}

//分页查询主机列表
func (h *handler) QueryHost(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
	var (
		pg = 20
		pn = 1
	)

	//query string
	qs := r.URL.Query()
	pgstr := qs.Get("page_size")
	if pgstr != "" {
		pg, _ = strconv.Atoi(pgstr)
	}
	pnstr := qs.Get("page_number")
	if pnstr != "" {
		pn, _ = strconv.Atoi(pnstr)
	}

	req := &host.QueryHostRequest{
		PageSize: pg,
		PageNum:  pn,
	}

	set, err := h.host.QueryHost(r.Context(), req)
	if err != nil {
		response.Failed(w, err)
		return
	}

	response.Success(w, set)
}
